/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sun.courier.view;

import com.sun.courier.DemoProperties;
import com.sun.courier.dal.CalculationDAL;
import com.sun.courier.entity.Calculation;
import com.sun.courier.model.ButtonsPanel;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
import com.sun.courier.model.ButtonsRenderer;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseListener;
import java.util.EventObject;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;

/**
 *
 * @author NamBH
 */
@DemoProperties(
        value = "Calculation",
        category = "Calculation Management",
        description = "Magage Calculation Information, Including: Insert, Update and Delete",
        sourceFiles = { //                "com/sun/courier/view/CalculationManagement.java",
//                "com/sun/courier/icons/Department.gif"
})
public class CalculationManagement extends JPanel {

    private CalculationDAL dalCalc = new CalculationDAL();
    private ArrayList<Calculation> lstCalc;
    private String[] Data = new String[4];

    public CalculationManagement() {
        createControlPanel();
        lstCalc = dalCalc.getAll();
        loadTable();
    }

    private void loadTable() {
        Vector cols = new Vector();
        cols.add("No");
        cols.add("Distance");
        cols.add("Charge Per Gram");
        cols.add("Action");

        Vector data = new Vector();
        int i = 1;
        for (Calculation item : lstCalc) {
            Vector row = new Vector();
            row.add(i++);
            row.add(item.getDistance());
            row.add(item.getChargePerGram());
            data.add(row);
        }

        DefaultTableModel tblModel = new DefaultTableModel(data, cols);
        tblItem.setModel(tblModel);

        tblItem.getColumnModel().getColumn(3).setCellRenderer(new ButtonsRenderer());
        tblItem.getColumnModel().getColumn(3).setCellEditor(new ActionButton());
    }

    //< Dialog >
    class Dialog extends JDialog {
    
        public Dialog() {
            init();
        }

  private void init() {
    
        jLabelDL4 = new javax.swing.JLabel();
        txtDistanceDL = new javax.swing.JTextField();
        txtChargePerGramDL = new javax.swing.JTextField();
        jLabelDL1 = new javax.swing.JLabel();
        jLabelDL2 = new javax.swing.JLabel();
        jLabelDL3 = new javax.swing.JLabel();
        btnUpdate = new javax.swing.JButton();
        btCancel = new javax.swing.JButton();
        jToolBar1 = new javax.swing.JToolBar();
        edit = new javax.swing.JLabel();

        jLabelDL4.setText("jLabel4");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabelDL1.setText("Distance:");

        jLabelDL2.setText("Changer per gram:");

        jLabelDL3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabelDL3.setForeground(new java.awt.Color(0, 0, 255));
        jLabelDL3.setText("Update Calulation");

        btnUpdate.setText("Update");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btCancel.setText("Cancel");
        btCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelActionPerformed(evt);
            }
        });

        jToolBar1.setRollover(true);

        edit.setText("Edit Calculation");
        jToolBar1.add(edit);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabelDL1)
                    .addComponent(jLabelDL2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelDL3)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(btnUpdate)
                        .addGap(34, 34, 34)
                        .addComponent(btCancel))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(txtDistanceDL)
                        .addComponent(txtChargePerGramDL, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)))
                .addContainerGap(24, Short.MAX_VALUE))
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabelDL3)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelDL1)
                    .addComponent(txtDistanceDL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtChargePerGramDL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelDL2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnUpdate)
                    .addComponent(btCancel))
                .addGap(18, 18, 18)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
  }
  
  //Action
  private void btCancelActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        this.setVisible(false);
    }
  
  private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt){
        lblMessage.setText("");
        int row = tblItem.getSelectedRow();
        if (row >= 0) {
            Calculation calculation = lstCalc.get(row);
            //getdata
            String distance = txtDistanceDL.getText();
            Double charge = txtChargePerGramDL.getText().isEmpty() ? null : Double.parseDouble(txtChargePerGramDL.getText());

            //validate
            boolean check = true;
            String message = "";

            if (check && distance.isEmpty()) {
                check = false;
                message = "Distance is required!";
                txtDistanceDL.requestFocus();
            }

            if (check && charge <= 0) {
                check = false;
                message = "Charge is required, is number and greater 0!";
                txtChargePerGramDL.requestFocus();
            }

            //process
            if (check) {
                calculation.setDistance(distance);
                calculation.setChargePerGram(charge);
                check &= dalCalc.edit(calculation);

                if (check) {
                    JOptionPane.showMessageDialog(null, "Edit calculation successful");
                    this.setVisible(false);
                    lstCalc = dalCalc.getAll();
                    loadTable();
                } else {
                    JOptionPane.showMessageDialog(null, "Edit calculation fail");
                }
            } else {
                lblMessage.setText(message);
            }
        } else {
            JOptionPane.showMessageDialog(null, "You must seleted a calculation");
        }
      
    }
    }
 
 
    
    //< End >
    
    // <editor-fold defaultstate="collapsed" desc="Action">
    class ActionButton extends ButtonsPanel implements TableCellEditor {

        transient protected ChangeEvent changeEvent = null;

        public ActionButton() {
            super();

            //---->
            //DEBUG: view button click -> control key down + edit button(same cell) press -> remain selection color
            MouseListener ml = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    ButtonModel m = ((JButton) e.getSource()).getModel();
                    if (m.isPressed() && tblItem.isRowSelected(tblItem.getEditingRow()) && e.isControlDown()) {
                        setBackground(tblItem.getBackground());
                    }
                }
            };
            buttons.get(0).addMouseListener(ml);
            buttons.get(0).addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    btnDeleteActionPerformed(ae);
                }
            });
            buttons.get(1).addMouseListener(ml);
            buttons.get(1).addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    btnEditActionPerformed(ae);
                }
            });
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            this.setBackground(table.getSelectionBackground());
            return this;
        }

        @Override
        public Object getCellEditorValue() {
            return "";
        }

        //Copid from AbstractCellEditor
        //protected EventListenerList listenerList = new EventListenerList();
        //transient protected ChangeEvent changeEvent = null;
        @Override
        public boolean isCellEditable(EventObject e) {
            return true;
        }

        @Override
        public boolean shouldSelectCell(EventObject anEvent) {
            return true;
        }

        @Override
        public boolean stopCellEditing() {
            fireEditingStopped();
            return true;
        }

        @Override
        public void cancelCellEditing() {
            fireEditingCanceled();
        }

        @Override
        public void addCellEditorListener(CellEditorListener l) {
            listenerList.add(CellEditorListener.class, l);
        }

        @Override
        public void removeCellEditorListener(CellEditorListener l) {
            listenerList.remove(CellEditorListener.class, l);
        }

        public CellEditorListener[] getCellEditorListeners() {
            return listenerList.getListeners(CellEditorListener.class);
        }

        protected void fireEditingStopped() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    // Lazily create the event:
                    if (changeEvent == null) {
                        changeEvent = new ChangeEvent(this);
                    }
                    ((CellEditorListener) listeners[i + 1]).editingStopped(changeEvent);
                }
            }
        }

        protected void fireEditingCanceled() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    // Lazily create the event:
                    if (changeEvent == null) {
                        changeEvent = new ChangeEvent(this);
                    }
                    ((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent);
                }
            }
        }
    }// </editor-fold>

    private void btnAddActionPerformed(ActionEvent evt) {
        lblMessage.setText("");

        //getdata
        String distance = txtDistance.getText();
        Float charge = txtChargePerGram.getText().isEmpty() ? null : Float.parseFloat(txtChargePerGram.getText());

        //validate
        boolean check = true;
        String message = "";

        if (check && distance.isEmpty()) {
            check = false;
            message = "Distance is required!";
            txtDistance.requestFocus();
        }

        if (check && charge <= 0) {
            check = false;
            message = "Charge is required, is number and greater 0!";
            txtChargePerGram.requestFocus();
        }

        //process
        if (check) {
            check &= dalCalc.add(new Calculation(0, distance, charge));

            if (check) {
                JOptionPane.showMessageDialog(null, "Add calculation successful");

                lstCalc = dalCalc.getAll();
                loadTable();
            } else {
                JOptionPane.showMessageDialog(null, "Add calculation fail");
            }
        } else {
            lblMessage.setText(message);
        }
    }

    private void btnEditActionPerformed(ActionEvent evt) {
        //---------------
        Dimension ad = new Dimension(450, 170);
        Dialog dialog = new Dialog();
        int row = tblItem.getSelectedRow();
        if (row >= 0) {
        dialog.setLocation(500, 200);
        dialog.setMaximumSize(ad);
        dialog.setMinimumSize(ad);       
        dialog.setVisible(true);
            Calculation dep = lstCalc.get(row);
            txtDistanceDL.setText(dep.getDistance());
            txtChargePerGramDL.setText(dep.getChargePerGram() + "");
        }
    }
       private void btnDeleteActionPerformed(ActionEvent evt) {
        int row = tblItem.getSelectedRow();
        if (row >= 0) {
            int confirm = JOptionPane.showConfirmDialog(null, "Are you sure delete this?", "Delete", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                boolean check = dalCalc.delete(lstCalc.get(row).getId());

                if (check) {
                    JOptionPane.showMessageDialog(null, "Delete calculation successful");

                    lstCalc = dalCalc.getAll();
                    loadTable();
                } else {
                    JOptionPane.showMessageDialog(null, "Delete calculation fail");
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "You must seleted a department");
        }
  }

    private void tblItemMouseClicked(MouseEvent evt) {
        int row = tblItem.getSelectedRow();
        if (row >= 0) {
            Calculation dep = lstCalc.get(row);
            txtDistanceDL.setText(dep.getDistance());
            txtChargePerGramDL.setText(Double.toString(dep.getChargePerGram()));
        }
    }

    private void txtChargePerGramKeyPressed(KeyEvent e) {
        if (!Character.isDigit(e.getKeyChar())) {
            e.consume();
        }
    }

    protected void createControlPanel() {
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtDistance = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtChargePerGram = new javax.swing.JTextField();
        lblMessage = new javax.swing.JLabel();
        btnAdd = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblItem = new javax.swing.JTable();

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel2.setText("Distance:");

        jLabel3.setText("Charge Per Gram: ");

        txtChargePerGram.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtChargePerGramKeyPressed(evt);
            }
        });

        lblMessage.setForeground(new java.awt.Color(255, 0, 0));
        lblMessage.setText(" ");

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtDistance, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtChargePerGram, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
                .addComponent(lblMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap()));
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(txtDistance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel3)
                .addComponent(txtChargePerGram, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(btnAdd))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblMessage)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        tblItem.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
            {},
            {},
            {},
            {}
        },
                new String[]{}));
        tblItem.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblItemMouseClicked(evt);
            }
        });
        tblItem.setRowHeight(35);
        jScrollPane1.setViewportView(tblItem);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)));
    }
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblMessage;
    private javax.swing.JTable tblItem;
    private javax.swing.JTextField txtDistance;
    private javax.swing.JTextField txtChargePerGram;
    
    //dialog
    private javax.swing.JButton btCancel;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JLabel edit;
    private javax.swing.JLabel jLabelDL1;
    private javax.swing.JLabel jLabelDL2;
    private javax.swing.JLabel jLabelDL3;
    private javax.swing.JLabel jLabelDL4;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField txtChargePerGramDL;
    private javax.swing.JTextField txtDistanceDL;
    
    public static void main(String[] args) {
        JFrame f = new JFrame();
        CalculationManagement cal = new CalculationManagement();
        cal.setPreferredSize(new Dimension(300, 300));
        f.add(cal);
        f.setPreferredSize(new Dimension(300, 300));
        f.setVisible(true);
    }
}
